{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "02a561f4",
   "metadata": {},
   "source": [
    "# Create a RAG system using OpenVINO and LlamaIndex\n",
    "\n",
    "**Retrieval-augmented generation (RAG)** is a technique for augmenting LLM knowledge with additional, often private or real-time, data. LLMs can reason about wide-ranging topics, but their knowledge is limited to the public data up to a specific point in time that they were trained on. If you want to build AI applications that can reason about private data or data introduced after a model’s cutoff date, you need to augment the knowledge of the model with the specific information it needs. The process of bringing the appropriate information and inserting it into the model prompt is known as Retrieval Augmented Generation (RAG).\n",
    "\n",
    "[LlamaIndex](https://docs.llamaindex.ai/en/stable/) is a framework for building context-augmented generative AI applications with LLMs.LlamaIndex imposes no restriction on how you use LLMs. You can use LLMs as auto-complete, chatbots, semi-autonomous agents, and more. It just makes using them easier. \n",
    "\n",
    "The tutorial consists of the following steps:\n",
    "\n",
    "- Install prerequisites\n",
    "- Download and convert the model from a public source using the [OpenVINO integration with Hugging Face Optimum](https://huggingface.co/blog/openvino).\n",
    "- Compress model weights to 4-bit or 8-bit data types using [NNCF](https://github.com/openvinotoolkit/nncf)\n",
    "- Create a RAG chain pipeline\n",
    "- Run Q&A pipeline\n",
    "\n",
    "In this example, the customized RAG pipeline consists of following components in order, where embedding, rerank and LLM will be deployed with OpenVINO to optimize their inference performance.\n",
    "\n",
    "![RAG](https://github.com/openvinotoolkit/openvino_notebooks/assets/91237924/0076f6c7-75e4-4c2e-9015-87b355e5ca28)\n",
    "\n",
    "#### Table of contents:\n",
    "\n",
    "- [Prerequisites](#Prerequisites)\n",
    "- [Select model for inference](#Select-model-for-inference)\n",
    "- [login to huggingfacehub to get access to pretrained model](#login-to-huggingfacehub-to-get-access-to-pretrained-model)\n",
    "- [Convert model and compress model weights](#convert-model-and-compress-model-weights)\n",
    "  - [LLM conversion and Weights Compression using Optimum-CLI](#LLM-conversion-and-Weights-Compression-using-Optimum-CLI)\n",
    "    - [Weight compression with AWQ](#Weight-compression-with-AWQ)\n",
    "  - [Convert embedding model using Optimum-CLI](#Convert-embedding-model-using-Optimum-CLI)\n",
    "  - [Convert rerank model using Optimum-CLI](#Convert-rerank-model-using-Optimum-CLI)\n",
    "- [Select device for inference and model variant](#Select-device-for-inference-and-model-variant)\n",
    "  - [Select device for embedding model inference](#Select-device-for-embedding-model-inference)\n",
    "  - [Select device for rerank model inference](#Select-device-for-rerank-model-inference)\n",
    "  - [Select device for LLM model inference](#Select-device-for-LLM-model-inference)\n",
    "- [Load model](#Load-model)\n",
    "  - [Load embedding model](#Load-embedding-model)\n",
    "  - [Load rerank model](#Load-rerank-model)\n",
    "  - [Load LLM model](#Load-LLM-model)\n",
    "- [Run QA over Document](#Run-QA-over-Document)\n",
    "- [Gradio Demo](#Gradio-Demo)\n",
    "\n",
    "### Installation Instructions\n",
    "\n",
    "This is a self-contained example that relies solely on its own code.\n",
    "\n",
    "We recommend  running the notebook in a virtual environment. You only need a Jupyter server to start.\n",
    "For details, please refer to [Installation Guide](https://github.com/openvinotoolkit/openvino_notebooks/blob/latest/README.md#-installation-guide).\n",
    "\n",
    "<img referrerpolicy=\"no-referrer-when-downgrade\" src=\"https://static.scarf.sh/a.png?x-pxid=5b5a4db0-7875-4bfb-bdbd-01698b5b1a77&file=notebooks/llm-rag-llamaindex/llm-rag-llamaindex.ipynb\" />\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "7c09cb8f",
   "metadata": {},
   "source": [
    "## Prerequisites\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Install required dependencies\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1f077b32-5d36-44b0-9041-407e996283a3",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Note: you may need to restart the kernel to use updated packages.\n",
      "Note: you may need to restart the kernel to use updated packages.\n",
      "Note: you may need to restart the kernel to use updated packages.\n",
      "Note: you may need to restart the kernel to use updated packages.\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "import requests\n",
    "from pathlib import Path\n",
    "\n",
    "os.environ[\"GIT_CLONE_PROTECTION_ACTIVE\"] = \"false\"\n",
    "\n",
    "if not Path(\"notebook_utils.py\").exists():\n",
    "    r = requests.get(\n",
    "        url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/notebook_utils.py\",\n",
    "    )\n",
    "    with open(\"notebook_utils.py\", \"w\") as f:\n",
    "        f.write(r.text)\n",
    "\n",
    "if not Path(\"pip_helper.py\").exists():\n",
    "    r = requests.get(\n",
    "        url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/pip_helper.py\",\n",
    "    )\n",
    "    open(\"pip_helper.py\", \"w\").write(r.text)\n",
    "\n",
    "from pip_helper import pip_install\n",
    "\n",
    "pip_install(\n",
    "    \"-qU\",\n",
    "    \"--extra-index-url\",\n",
    "    \"https://download.pytorch.org/whl/cpu\",\n",
    "    \"nncf>=2.18.0\",\n",
    "    \"torch==2.8\",\n",
    "    \"torchvision==0.23.0\",\n",
    "    \"transformers==4.53.3\",\n",
    "    \"llama-index\",\n",
    "    \"faiss-cpu\",\n",
    "    \"pymupdf\",\n",
    "    \"langchain<1.0\",\n",
    "    \"llama-index-readers-file\",\n",
    "    \"llama-index-vector-stores-faiss\",\n",
    "    \"llama-index-llms-langchain\",\n",
    "    \"llama-index-llms-huggingface>=0.4.0,<0.5.0\",\n",
    "    \"llama-index-embeddings-huggingface>=0.4.0,<0.5.0\",\n",
    ")\n",
    "pip_install(\"-q\", \"git+https://github.com/huggingface/optimum-intel.git\", \"datasets<4.0.0\", \"accelerate\", \"gradio<6\")\n",
    "pip_install(\"--pre\", \"-U\", \"openvino>=2025.2\", \"--extra-index-url\", \"https://storage.openvinotoolkit.org/simple/wheels/nightly\")\n",
    "pip_install(\n",
    "    \"--pre\",\n",
    "    \"-U\",\n",
    "    \"huggingface-hub>=0.26.5,<1.0\",\n",
    "    \"openvino-tokenizers[transformers]>=2025.2\",\n",
    "    \"openvino-genai>=2025.2\",\n",
    "    \"--extra-index-url\",\n",
    "    \"https://storage.openvinotoolkit.org/simple/wheels/nightly\",\n",
    ")\n",
    "pip_install(\"-q\", \"--no-deps\", \"llama-index-llms-openvino>=0.3.1\", \"llama-index-embeddings-openvino>=0.2.1\", \"llama-index-postprocessor-openvino-rerank>=0.2.0\")\n",
    "\n",
    "# Read more about telemetry collection at https://github.com/openvinotoolkit/openvino_notebooks?tab=readme-ov-file#-telemetry\n",
    "from notebook_utils import collect_telemetry\n",
    "\n",
    "collect_telemetry(\"llm-rag-llamaindex.ipynb\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "1b2c3f4e",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "LLM config will be updated\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "from pathlib import Path\n",
    "import requests\n",
    "import shutil\n",
    "import io\n",
    "\n",
    "# fetch model configuration\n",
    "\n",
    "config_shared_path = Path(\"../../utils/llm_config.py\")\n",
    "config_dst_path = Path(\"llm_config.py\")\n",
    "text_example_en_path = Path(\"text_example_en.pdf\")\n",
    "text_example_cn_path = Path(\"text_example_cn.pdf\")\n",
    "text_example_en = \"https://github.com/openvinotoolkit/openvino_notebooks/files/15039728/Platform.Brief_Intel.vPro.with.Intel.Core.Ultra_Final.pdf\"\n",
    "text_example_cn = \"https://github.com/openvinotoolkit/openvino_notebooks/files/15039713/Platform.Brief_Intel.vPro.with.Intel.Core.Ultra_Final_CH.pdf\"\n",
    "\n",
    "if not config_dst_path.exists():\n",
    "    if config_shared_path.exists():\n",
    "        try:\n",
    "            os.symlink(config_shared_path, config_dst_path)\n",
    "        except Exception:\n",
    "            shutil.copy(config_shared_path, config_dst_path)\n",
    "    else:\n",
    "        r = requests.get(url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/llm_config.py\")\n",
    "        with open(\"llm_config.py\", \"w\", encoding=\"utf-8\") as f:\n",
    "            f.write(r.text)\n",
    "elif not os.path.islink(config_dst_path):\n",
    "    print(\"LLM config will be updated\")\n",
    "    if config_shared_path.exists():\n",
    "        shutil.copy(config_shared_path, config_dst_path)\n",
    "    else:\n",
    "        r = requests.get(url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/llm_config.py\")\n",
    "        with open(\"llm_config.py\", \"w\", encoding=\"utf-8\") as f:\n",
    "            f.write(r.text)\n",
    "\n",
    "\n",
    "if not text_example_en_path.exists():\n",
    "    r = requests.get(url=text_example_en)\n",
    "    content = io.BytesIO(r.content)\n",
    "    with open(\"text_example_en.pdf\", \"wb\") as f:\n",
    "        f.write(content.read())\n",
    "\n",
    "if not text_example_cn_path.exists():\n",
    "    r = requests.get(url=text_example_cn)\n",
    "    content = io.BytesIO(r.content)\n",
    "    with open(\"text_example_cn.pdf\", \"wb\") as f:\n",
    "        f.write(content.read())"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c8e7965f",
   "metadata": {},
   "source": [
    "## Select model for inference\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "The tutorial supports different models, you can select one from the provided options to compare the quality of open source LLM solutions.\n",
    "\n",
    "> **Note**: conversion of some models can require additional actions from user side and at least 64GB RAM for conversion.\n",
    "\n",
    "The available embedding model options are:\n",
    "\n",
    "- [**bge-small-en-v1.5**](https://huggingface.co/BAAI/bge-small-en-v1.5)\n",
    "- [**bge-small-zh-v1.5**](https://huggingface.co/BAAI/bge-small-zh-v1.5)\n",
    "- [**bge-large-en-v1.5**](https://huggingface.co/BAAI/bge-large-en-v1.5)\n",
    "- [**bge-large-zh-v1.5**](https://huggingface.co/BAAI/bge-large-zh-v1.5)\n",
    "- [**bge-m3**](https://huggingface.co/BAAI/bge-m3)\n",
    "\n",
    "BGE embedding is a general Embedding Model. The model is pre-trained using RetroMAE and trained on large-scale pair data using contrastive learning.\n",
    "\n",
    "The available rerank model options are:\n",
    "\n",
    "- [**bge-reranker-v2-m3**](https://huggingface.co/BAAI/bge-reranker-v2-m3)\n",
    "- [**bge-reranker-large**](https://huggingface.co/BAAI/bge-reranker-large)\n",
    "- [**bge-reranker-base**](https://huggingface.co/BAAI/bge-reranker-base)\n",
    "\n",
    "Reranker model with cross-encoder will perform full-attention over the input pair, which is more accurate than embedding model (i.e., bi-encoder) but more time-consuming than embedding model. Therefore, it can be used to re-rank the top-k documents returned by embedding model.\n",
    "\n",
    "You can also find available LLM model options in [llm-chatbot](../llm-chatbot/README.md) notebook.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "d3b57cfb-e727-43a5-b2c9-8f1b1ba72061",
   "metadata": {},
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "import ipywidgets as widgets\n",
    "from notebook_utils import device_widget, optimize_bge_embedding"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "b51ff5a9",
   "metadata": {},
   "source": [
    "## Convert model and compress model weights\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "The Weights Compression algorithm is aimed at compressing the weights of the models and can be used to optimize the model footprint and performance of large models where the size of weights is relatively larger than the size of activations, for example, Large Language Models (LLM). Compared to INT8 compression, INT4 compression improves performance even more, but introduces a minor drop in prediction quality."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "37bf49d7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "f2585df593974493ba0f94ef53792b79",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Model Language:', options=('English', 'Chinese', 'Japanese'), value='English')"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from llm_config import (\n",
    "    SUPPORTED_EMBEDDING_MODELS,\n",
    "    SUPPORTED_RERANK_MODELS,\n",
    "    SUPPORTED_LLM_MODELS,\n",
    ")\n",
    "\n",
    "model_languages = list(SUPPORTED_LLM_MODELS)\n",
    "\n",
    "model_language = widgets.Dropdown(\n",
    "    options=model_languages,\n",
    "    value=model_languages[0],\n",
    "    description=\"Model Language:\",\n",
    "    disabled=False,\n",
    ")\n",
    "\n",
    "model_language"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "184d1678-0e73-4f35-8af5-1a7d291c2e6e",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ff3b955872b045efa6558ec73fb7ab89",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Model:', index=13, options=('tiny-llama-1b-chat', 'gemma-2b-it', 'red-pajama-3b-chat', '…"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "llm_model_ids = [model_id for model_id, model_config in SUPPORTED_LLM_MODELS[model_language.value].items() if model_config.get(\"rag_prompt_template\")]\n",
    "\n",
    "llm_model_id = widgets.Dropdown(\n",
    "    options=llm_model_ids,\n",
    "    value=llm_model_ids[0],\n",
    "    description=\"Model:\",\n",
    "    disabled=False,\n",
    ")\n",
    "\n",
    "llm_model_id"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "49ea95f8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Selected LLM model phi-3-mini-instruct\n"
     ]
    }
   ],
   "source": [
    "llm_model_configuration = SUPPORTED_LLM_MODELS[model_language.value][llm_model_id.value]\n",
    "print(f\"Selected LLM model {llm_model_id.value}\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "5d370f13",
   "metadata": {},
   "source": [
    "🤗 [Optimum Intel](https://huggingface.co/docs/optimum/intel/index) is the interface between the 🤗 [Transformers](https://huggingface.co/docs/transformers/index) and [Diffusers](https://huggingface.co/docs/diffusers/index) libraries and OpenVINO to accelerate end-to-end pipelines on Intel architectures. It provides ease-to-use cli interface for exporting models to [OpenVINO Intermediate Representation (IR)](https://docs.openvino.ai/2024/documentation/openvino-ir-format.html) format.\n",
    "\n",
    "The command bellow demonstrates basic command for model export with `optimum-cli`\n",
    "\n",
    "```\n",
    "optimum-cli export openvino --model <model_id_or_path> --task <task> <out_dir>\n",
    "```\n",
    "\n",
    "where `--model` argument is model id from HuggingFace Hub or local directory with model (saved using `.save_pretrained` method), `--task ` is one of [supported task](https://huggingface.co/docs/optimum/exporters/task_manager) that exported model should solve. For LLMs it will be `text-generation-with-past`. If model initialization requires to use remote code, `--trust-remote-code` flag additionally should be passed.\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "6337eab8",
   "metadata": {},
   "source": [
    "### LLM conversion and Weights Compression using Optimum-CLI\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "You can also apply fp16, 8-bit or 4-bit weight compression on the Linear, Convolutional and Embedding layers when exporting your model with the CLI by setting `--weight-format` to respectively fp16, int8 or int4. This type of optimization allows to reduce the memory footprint and inference latency.\n",
    "By default the quantization scheme for int8/int4 will be [asymmetric](https://github.com/openvinotoolkit/nncf/blob/develop/docs/compression_algorithms/Quantization.md#asymmetric-quantization), to make it [symmetric](https://github.com/openvinotoolkit/nncf/blob/develop/docs/compression_algorithms/Quantization.md#symmetric-quantization) you can add `--sym`.\n",
    "\n",
    "For INT4 quantization you can also specify the following arguments :\n",
    "\n",
    "- The `--group-size` parameter will define the group size to use for quantization, -1 it will results in per-column quantization.\n",
    "- The `--ratio` parameter controls the ratio between 4-bit and 8-bit quantization. If set to 0.9, it means that 90% of the layers will be quantized to int4 while 10% will be quantized to int8.\n",
    "\n",
    "Smaller group_size and ratio values usually improve accuracy at the sacrifice of the model size and inference latency.\n",
    "\n",
    "> **Note**: There may be no speedup for INT4/INT8 compressed models on dGPU.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "c6a38153",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "fb739056bc904bb5a7704ad4b87dd3f9",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Checkbox(value=True, description='Prepare INT4 model')"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "f82e1e2fe0c24cd49ae0f2e3436f0bba",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Checkbox(value=False, description='Prepare INT8 model')"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "37ec7f3c0d4141c9acfd86c5996a5971",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Checkbox(value=False, description='Prepare FP16 model')"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Markdown, display\n",
    "\n",
    "prepare_int4_model = widgets.Checkbox(\n",
    "    value=True,\n",
    "    description=\"Prepare INT4 model\",\n",
    "    disabled=False,\n",
    ")\n",
    "prepare_int8_model = widgets.Checkbox(\n",
    "    value=False,\n",
    "    description=\"Prepare INT8 model\",\n",
    "    disabled=False,\n",
    ")\n",
    "prepare_fp16_model = widgets.Checkbox(\n",
    "    value=False,\n",
    "    description=\"Prepare FP16 model\",\n",
    "    disabled=False,\n",
    ")\n",
    "\n",
    "display(prepare_int4_model)\n",
    "display(prepare_int8_model)\n",
    "display(prepare_fp16_model)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "65ffe10b",
   "metadata": {},
   "source": [
    "#### Weight compression with AWQ\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "[Activation-aware Weight Quantization](https://arxiv.org/abs/2306.00978) (AWQ) is an algorithm that tunes model weights for more accurate INT4 compression. It slightly improves generation quality of compressed LLMs, but requires significant additional time for tuning weights on a calibration dataset. We use `wikitext-2-raw-v1/train` subset of the [Wikitext](https://huggingface.co/datasets/Salesforce/wikitext) dataset for calibration.\n",
    "\n",
    "Below you can enable AWQ to be additionally applied during model export with INT4 precision.\n",
    "\n",
    ">**Note**: Applying AWQ requires significant memory and time.\n",
    "\n",
    ">**Note**: It is possible that there will be no matching patterns in the model to apply AWQ, in such case it will be skipped."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "e4531bbd67d8753d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "631f734375ee45d483beb1bc7aa65185",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Checkbox(value=False, description='Enable AWQ')"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "enable_awq = widgets.Checkbox(\n",
    "    value=False,\n",
    "    description=\"Enable AWQ\",\n",
    "    disabled=not prepare_int4_model.value,\n",
    ")\n",
    "display(enable_awq)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "2020d522",
   "metadata": {},
   "outputs": [],
   "source": [
    "pt_model_id = llm_model_configuration[\"model_id\"]\n",
    "pt_model_name = llm_model_id.value.split(\"-\")[0]\n",
    "fp16_model_dir = Path(llm_model_id.value) / \"FP16\"\n",
    "int8_model_dir = Path(llm_model_id.value) / \"INT8_compressed_weights\"\n",
    "int4_model_dir = Path(llm_model_id.value) / \"INT4_compressed_weights\"\n",
    "\n",
    "\n",
    "def convert_to_fp16():\n",
    "    if (fp16_model_dir / \"openvino_model.xml\").exists():\n",
    "        return\n",
    "    remote_code = llm_model_configuration.get(\"remote_code\", False)\n",
    "    export_command_base = \"optimum-cli export openvino --model {} --task text-generation-with-past --weight-format fp16\".format(pt_model_id)\n",
    "    if remote_code:\n",
    "        export_command_base += \" --trust-remote-code\"\n",
    "    export_command = export_command_base + \" \" + str(fp16_model_dir)\n",
    "    display(Markdown(\"**Export command:**\"))\n",
    "    display(Markdown(f\"`{export_command}`\"))\n",
    "    ! $export_command\n",
    "\n",
    "\n",
    "def convert_to_int8():\n",
    "    if (int8_model_dir / \"openvino_model.xml\").exists():\n",
    "        return\n",
    "    int8_model_dir.mkdir(parents=True, exist_ok=True)\n",
    "    remote_code = llm_model_configuration.get(\"remote_code\", False)\n",
    "    export_command_base = \"optimum-cli export openvino --model {} --task text-generation-with-past --weight-format int8\".format(pt_model_id)\n",
    "    if remote_code:\n",
    "        export_command_base += \" --trust-remote-code\"\n",
    "    export_command = export_command_base + \" \" + str(int8_model_dir)\n",
    "    display(Markdown(\"**Export command:**\"))\n",
    "    display(Markdown(f\"`{export_command}`\"))\n",
    "    ! $export_command\n",
    "\n",
    "\n",
    "def convert_to_int4():\n",
    "    compression_configs = {\n",
    "        \"zephyr-7b-beta\": {\n",
    "            \"sym\": True,\n",
    "            \"group_size\": 64,\n",
    "            \"ratio\": 0.6,\n",
    "        },\n",
    "        \"mistral-7b\": {\n",
    "            \"sym\": True,\n",
    "            \"group_size\": 64,\n",
    "            \"ratio\": 0.6,\n",
    "        },\n",
    "        \"minicpm-2b-dpo\": {\n",
    "            \"sym\": True,\n",
    "            \"group_size\": 64,\n",
    "            \"ratio\": 0.6,\n",
    "        },\n",
    "        \"gemma-2b-it\": {\n",
    "            \"sym\": True,\n",
    "            \"group_size\": 64,\n",
    "            \"ratio\": 0.6,\n",
    "        },\n",
    "        \"notus-7b-v1\": {\n",
    "            \"sym\": True,\n",
    "            \"group_size\": 64,\n",
    "            \"ratio\": 0.6,\n",
    "        },\n",
    "        \"neural-chat-7b-v3-1\": {\n",
    "            \"sym\": True,\n",
    "            \"group_size\": 64,\n",
    "            \"ratio\": 0.6,\n",
    "        },\n",
    "        \"llama-2-chat-7b\": {\n",
    "            \"sym\": True,\n",
    "            \"group_size\": 128,\n",
    "            \"ratio\": 0.8,\n",
    "        },\n",
    "        \"llama-3-8b-instruct\": {\n",
    "            \"sym\": True,\n",
    "            \"group_size\": 128,\n",
    "            \"ratio\": 0.8,\n",
    "        },\n",
    "        \"gemma-7b-it\": {\n",
    "            \"sym\": True,\n",
    "            \"group_size\": 128,\n",
    "            \"ratio\": 0.8,\n",
    "        },\n",
    "        \"chatglm2-6b\": {\n",
    "            \"sym\": True,\n",
    "            \"group_size\": 128,\n",
    "            \"ratio\": 0.72,\n",
    "        },\n",
    "        \"qwen-7b-chat\": {\"sym\": True, \"group_size\": 128, \"ratio\": 0.6},\n",
    "        \"red-pajama-3b-chat\": {\n",
    "            \"sym\": False,\n",
    "            \"group_size\": 128,\n",
    "            \"ratio\": 0.5,\n",
    "        },\n",
    "        \"qwen2.5-7b-instruct\": {\"sym\": True, \"group_size\": 128, \"ratio\": 1.0},\n",
    "        \"qwen2.5-3b-instruct\": {\"sym\": True, \"group_size\": 128, \"ratio\": 1.0},\n",
    "        \"qwen2.5-14b-instruct\": {\"sym\": True, \"group_size\": 128, \"ratio\": 1.0},\n",
    "        \"qwen2.5-1.5b-instruct\": {\"sym\": True, \"group_size\": 128, \"ratio\": 1.0},\n",
    "        \"qwen2.5-0.5b-instruct\": {\"sym\": True, \"group_size\": 128, \"ratio\": 1.0},\n",
    "        \"default\": {\n",
    "            \"sym\": False,\n",
    "            \"group_size\": 128,\n",
    "            \"ratio\": 0.8,\n",
    "        },\n",
    "    }\n",
    "\n",
    "    model_compression_params = compression_configs.get(llm_model_id.value, compression_configs[\"default\"])\n",
    "    if (int4_model_dir / \"openvino_model.xml\").exists():\n",
    "        return\n",
    "    remote_code = llm_model_configuration.get(\"remote_code\", False)\n",
    "    export_command_base = \"optimum-cli export openvino --model {} --task text-generation-with-past --weight-format int4\".format(pt_model_id)\n",
    "    int4_compression_args = \" --group-size {} --ratio {}\".format(model_compression_params[\"group_size\"], model_compression_params[\"ratio\"])\n",
    "    if model_compression_params[\"sym\"]:\n",
    "        int4_compression_args += \" --sym\"\n",
    "    if enable_awq.value:\n",
    "        int4_compression_args += \" --awq --dataset wikitext2 --num-samples 128\"\n",
    "    export_command_base += int4_compression_args\n",
    "    if remote_code:\n",
    "        export_command_base += \" --trust-remote-code\"\n",
    "    export_command = export_command_base + \" \" + str(int4_model_dir)\n",
    "    display(Markdown(\"**Export command:**\"))\n",
    "    display(Markdown(f\"`{export_command}`\"))\n",
    "    ! $export_command\n",
    "\n",
    "\n",
    "if prepare_fp16_model.value:\n",
    "    convert_to_fp16()\n",
    "if prepare_int8_model.value:\n",
    "    convert_to_int8()\n",
    "if prepare_int4_model.value:\n",
    "    convert_to_int4()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "f1d1d1a2",
   "metadata": {},
   "source": [
    "Let's compare model size for different compression types\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "8e127215",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Size of model with INT4 compressed weights is 2319.41 MB\n"
     ]
    }
   ],
   "source": [
    "fp16_weights = fp16_model_dir / \"openvino_model.bin\"\n",
    "int8_weights = int8_model_dir / \"openvino_model.bin\"\n",
    "int4_weights = int4_model_dir / \"openvino_model.bin\"\n",
    "\n",
    "if fp16_weights.exists():\n",
    "    print(f\"Size of FP16 model is {fp16_weights.stat().st_size / 1024 / 1024:.2f} MB\")\n",
    "for precision, compressed_weights in zip([8, 4], [int8_weights, int4_weights]):\n",
    "    if compressed_weights.exists():\n",
    "        print(f\"Size of model with INT{precision} compressed weights is {compressed_weights.stat().st_size / 1024 / 1024:.2f} MB\")\n",
    "    if compressed_weights.exists() and fp16_weights.exists():\n",
    "        print(f\"Compression rate for INT{precision} model: {fp16_weights.stat().st_size / compressed_weights.stat().st_size:.3f}\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "4f943465",
   "metadata": {},
   "source": [
    "### Convert embedding model using Optimum-CLI\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Since some embedding models can only support limited languages, we can filter them out according the LLM you selected.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "49c28d3a",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "8c068840d89d4fbf929526cda71b5cc2",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Embedding Model:', options=('bge-small-en-v1.5', 'bge-large-en-v1.5', 'bge-m3'), value='…"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "embedding_model_id = list(SUPPORTED_EMBEDDING_MODELS[model_language.value])\n",
    "\n",
    "embedding_model_id = widgets.Dropdown(\n",
    "    options=embedding_model_id,\n",
    "    value=embedding_model_id[0],\n",
    "    description=\"Embedding Model:\",\n",
    "    disabled=False,\n",
    ")\n",
    "\n",
    "embedding_model_id"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "3594116d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Selected bge-small-en-v1.5 model\n"
     ]
    }
   ],
   "source": [
    "embedding_model_configuration = SUPPORTED_EMBEDDING_MODELS[model_language.value][embedding_model_id.value]\n",
    "print(f\"Selected {embedding_model_id.value} model\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "b2fbc403-1cac-4864-8965-ad2fea0fd1ca",
   "metadata": {},
   "source": [
    "OpenVINO embedding model and tokenizer can be exported by `feature-extraction` task with `optimum-cli`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "ff80e6eb-7923-40ef-93d8-5e6c56e50667",
   "metadata": {},
   "outputs": [],
   "source": [
    "export_command_base = \"optimum-cli export openvino --model {} --task feature-extraction\".format(embedding_model_configuration[\"model_id\"])\n",
    "export_command = export_command_base + \" \" + str(embedding_model_id.value)\n",
    "\n",
    "if not Path(embedding_model_id.value).exists():\n",
    "    ! $export_command"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "a2d818f0",
   "metadata": {},
   "source": [
    "### Convert rerank model using Optimum-CLI\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "id": "1b5b8840",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "6b48e002cefb4ccf943a26dcd1aa569b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Rerank Model:', options=('bge-reranker-v2-m3', 'bge-reranker-large', 'bge-reranker-base'…"
      ]
     },
     "execution_count": 14,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rerank_model_id = list(SUPPORTED_RERANK_MODELS)\n",
    "\n",
    "rerank_model_id = widgets.Dropdown(\n",
    "    options=rerank_model_id,\n",
    "    value=rerank_model_id[0],\n",
    "    description=\"Rerank Model:\",\n",
    "    disabled=False,\n",
    ")\n",
    "\n",
    "rerank_model_id"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "1ca6fe04",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Selected bge-reranker-v2-m3 model\n"
     ]
    }
   ],
   "source": [
    "rerank_model_configuration = SUPPORTED_RERANK_MODELS[rerank_model_id.value]\n",
    "print(f\"Selected {rerank_model_id.value} model\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "400dbff2-9915-4df0-a1ef-01cda3543b27",
   "metadata": {},
   "source": [
    "Since `rerank` model is sort of sentence classification task, its OpenVINO IR and tokenizer can be exported by `text-classification` task with `optimum-cli`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "id": "d0bab20b",
   "metadata": {},
   "outputs": [],
   "source": [
    "export_command_base = \"optimum-cli export openvino --model {} --task text-classification\".format(rerank_model_configuration[\"model_id\"])\n",
    "export_command = export_command_base + \" \" + str(rerank_model_id.value)\n",
    "\n",
    "if not Path(rerank_model_id.value).exists():\n",
    "    ! $export_command"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "749b5bbd",
   "metadata": {},
   "source": [
    "## Select device for inference and model variant\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "> **Note**: There may be no speedup for INT4/INT8 compressed models on dGPU.\n",
    "\n",
    "### Select device for embedding model inference\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "e11e73cf",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "ea10500501f74f0b885b2a96a1722b96",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Device:', options=('CPU', 'AUTO'), value='CPU')"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "embedding_device = device_widget()\n",
    "\n",
    "embedding_device"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "9ab29b85",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Embedding model will be loaded to CPU device for text embedding\n"
     ]
    }
   ],
   "source": [
    "print(f\"Embedding model will be loaded to {embedding_device.value} device for text embedding\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "b552a431",
   "metadata": {},
   "source": [
    "Optimize the BGE embedding model's parameter precision when loading model to NPU device."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "796cc3d1",
   "metadata": {},
   "outputs": [],
   "source": [
    "USING_NPU = embedding_device.value == \"NPU\"\n",
    "\n",
    "npu_embedding_dir = embedding_model_id.value + \"-npu\"\n",
    "npu_embedding_path = Path(npu_embedding_dir) / \"openvino_model.xml\"\n",
    "\n",
    "if USING_NPU and not Path(npu_embedding_dir).exists():\n",
    "    shutil.copytree(embedding_model_id.value, npu_embedding_dir)\n",
    "    optimize_bge_embedding(Path(embedding_model_id.value) / \"openvino_model.xml\", npu_embedding_path)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "81b2644c",
   "metadata": {},
   "source": [
    "### Select device for rerank model inference\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "e0a2586b-5811-420f-834a-2b68de207df7",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "f286384d5fae46fa9538e076406b560c",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Device:', options=('CPU', 'AUTO'), value='CPU')"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "rerank_device = device_widget()\n",
    "\n",
    "rerank_device"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "id": "7b7a76b2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Rerenk model will be loaded to CPU device for text reranking\n"
     ]
    }
   ],
   "source": [
    "print(f\"Rerenk model will be loaded to {rerank_device.value} device for text reranking\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "ef31656a",
   "metadata": {},
   "source": [
    "### Select device for LLM model inference\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "id": "6d044d01",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "d87ad6d98ef84dfabe63040088e2027d",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Device:', options=('CPU', 'AUTO'), value='CPU')"
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "llm_device = device_widget(\"CPU\", exclude=[\"NPU\"])\n",
    "llm_device"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "id": "348b90fe",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "LLM model will be loaded to CPU device for response generation\n"
     ]
    }
   ],
   "source": [
    "print(f\"LLM model will be loaded to {llm_device.value} device for response generation\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "bc225391",
   "metadata": {},
   "source": [
    "## Load models\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "### Load embedding model\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Embedding model can be run through the `OpenVINOGenAIEmbedding` class without PyTorch requirements.\n",
    "To run embedding model on NPU use [`OpenVINOEmbeddings`](https://docs.llamaindex.ai/en/stable/examples/embeddings/openvino/) class of LlamaIndex."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "df3e8fd1-d4c1-4e33-b46e-7840e392f8ee",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Compiling the model to CPU ...\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "384\n",
      "[-0.003275666618719697, -0.01169075071811676, 0.04155930131673813, -0.03814813867211342, 0.02418304793536663]\n"
     ]
    }
   ],
   "source": [
    "from llama_index.embeddings.huggingface_openvino import OpenVINOEmbedding\n",
    "from ov_llamaindex_helper import OpenVINOGenAIEmbedding\n",
    "\n",
    "embedding_model_name = npu_embedding_dir if USING_NPU else embedding_model_id.value\n",
    "batch_size = 1 if USING_NPU else 4\n",
    "\n",
    "\n",
    "if USING_NPU:\n",
    "    embedding = OpenVINOEmbedding(\n",
    "        model_id_or_path=embedding_model_name, embed_batch_size=batch_size, device=embedding_device.value, model_kwargs={\"compile\": False}\n",
    "    )\n",
    "    embedding._model.reshape(1, 512)\n",
    "    embedding._model.compile()\n",
    "else:\n",
    "    embedding = OpenVINOGenAIEmbedding(\n",
    "        model_path=embedding_model_name,\n",
    "        embed_batch_size=batch_size,\n",
    "        device=embedding_device.value,\n",
    "    )\n",
    "\n",
    "embeddings = embedding.get_text_embedding(\"Hello World!\")\n",
    "EMBEDDING_MODEL_HIDDEN_SIZE = len(embeddings)\n",
    "print(EMBEDDING_MODEL_HIDDEN_SIZE)\n",
    "print(embeddings[:5])"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "d1a1fd58",
   "metadata": {},
   "source": [
    "### Load rerank model\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Now a Hugging Face rerank model can be supported by OpenVINO via [GenAI](https://github.com/openvinotoolkit/openvino.genai) through `OpenVINOGenAIReranking` class. To run model on NPU use [`OpenVINORerank`](https://docs.llamaindex.ai/en/stable/examples/node_postprocessor/openvino_rerank/) class of LlamaIndex.\n",
    "\n",
    "> **Note**: Rerank can be skipped in RAG.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b67b39f2-8394-45fb-9b2b-ea63e267a2d3",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Compiling the model to CPU ...\n"
     ]
    }
   ],
   "source": [
    "from llama_index.postprocessor.openvino_rerank import OpenVINORerank\n",
    "from ov_llamaindex_helper import OpenVINOGenAIReranking\n",
    "\n",
    "if USING_NPU:\n",
    "    reranker = OpenVINORerank(model_id_or_path=rerank_model_id.value, device=rerank_device.value, top_n=2)\n",
    "else:\n",
    "    reranker = OpenVINOGenAIReranking(model_id_or_path=rerank_model_id.value, device=rerank_device.value, top_n=2)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "79fe990a",
   "metadata": {},
   "source": [
    "### Load LLM model\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "OpenVINO models can be run locally through the `HuggingFacePipeline` class. To deploy a model with OpenVINO, you can specify the `backend=\"openvino\"` parameter to trigger OpenVINO as backend inference framework.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "id": "90b968f3",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "e92163eb789c46a9bfd5e5ef1128c9f8",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Dropdown(description='Model to run:', options=('INT4',), value='INT4')"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "available_models = []\n",
    "if int4_model_dir.exists():\n",
    "    available_models.append(\"INT4\")\n",
    "if int8_model_dir.exists():\n",
    "    available_models.append(\"INT8\")\n",
    "if fp16_model_dir.exists():\n",
    "    available_models.append(\"FP16\")\n",
    "\n",
    "model_to_run = widgets.Dropdown(\n",
    "    options=available_models,\n",
    "    value=available_models[0],\n",
    "    description=\"Model to run:\",\n",
    "    disabled=False,\n",
    ")\n",
    "\n",
    "model_to_run"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "20fcc33c",
   "metadata": {},
   "source": [
    "OpenVINO models can be run locally through the `OpenVINOLLM` class in [LlamaIndex](https://docs.llamaindex.ai/en/stable/examples/llm/openvino/). If you have an Intel GPU, you can specify `device_map=\"gpu\"` to run inference on it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f7f708db-8de1-4efd-94b2-fcabc48d52f4",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/ethan/intel/openvino_notebooks/openvino_env/lib/python3.11/site-packages/pydantic/_internal/_fields.py:161: UserWarning: Field \"model_id\" has conflict with protected namespace \"model_\".\n",
      "\n",
      "You may be able to resolve this warning by setting `model_config['protected_namespaces'] = ()`.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Loading model from phi-3-mini-instruct/INT4_compressed_weights\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1ec9d400429e43a6a6c819b53c3a513b",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "configuration_phi3.py:   0%|          | 0.00/11.2k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "A new version of the following files was downloaded from https://huggingface.co/microsoft/Phi-3-mini-4k-instruct:\n",
      "- configuration_phi3.py\n",
      ". Make sure to double-check they do not contain any added malicious code. To avoid downloading new versions of the code file, you can pin a revision.\n",
      "Compiling the model to CPU ...\n",
      "Special tokens have been added in the vocabulary, make sure the associated word embeddings are fine-tuned or trained.\n",
      "/home/ethan/intel/openvino_notebooks/openvino_env/lib/python3.11/site-packages/transformers/generation/configuration_utils.py:515: UserWarning: `do_sample` is set to `False`. However, `temperature` is set to `0.7` -- this flag is only used in sample-based generation modes. You should set `do_sample=True` or unset `temperature`.\n",
      "  warnings.warn(\n",
      "/home/ethan/intel/openvino_notebooks/openvino_env/lib/python3.11/site-packages/transformers/generation/configuration_utils.py:520: UserWarning: `do_sample` is set to `False`. However, `top_p` is set to `0.95` -- this flag is only used in sample-based generation modes. You should set `do_sample=True` or unset `top_p`.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "4\n"
     ]
    }
   ],
   "source": [
    "from llama_index.llms.openvino import OpenVINOLLM\n",
    "\n",
    "import openvino.properties as props\n",
    "import openvino.properties.hint as hints\n",
    "import openvino.properties.streams as streams\n",
    "import openvino\n",
    "\n",
    "core = openvino.Core()\n",
    "\n",
    "if model_to_run.value == \"INT4\":\n",
    "    model_dir = int4_model_dir\n",
    "elif model_to_run.value == \"INT8\":\n",
    "    model_dir = int8_model_dir\n",
    "else:\n",
    "    model_dir = fp16_model_dir\n",
    "print(f\"Loading model from {model_dir}\")\n",
    "\n",
    "ov_config = {hints.performance_mode(): hints.PerformanceMode.LATENCY, streams.num(): \"1\", props.cache_dir(): \"\"}\n",
    "\n",
    "stop_tokens = llm_model_configuration.get(\"stop_tokens\")\n",
    "completion_to_prompt = llm_model_configuration.get(\"completion_to_prompt\")\n",
    "\n",
    "if \"GPU\" in llm_device.value and \"qwen2-7b-instruct\" in llm_model_id.value:\n",
    "    ov_config[\"GPU_ENABLE_SDPA_OPTIMIZATION\"] = \"NO\"\n",
    "\n",
    "# On a GPU device a model is executed in FP16 precision. For red-pajama-3b-chat model there known accuracy\n",
    "# issues caused by this, which we avoid by setting precision hint to \"f32\".\n",
    "if llm_model_id.value == \"red-pajama-3b-chat\" and \"GPU\" in core.available_devices and llm_device.value in [\"GPU\", \"AUTO\"]:\n",
    "    ov_config[\"INFERENCE_PRECISION_HINT\"] = \"f32\"\n",
    "\n",
    "llm = OpenVINOLLM(\n",
    "    model_id_or_path=str(model_dir),\n",
    "    context_window=3900,\n",
    "    max_new_tokens=2,\n",
    "    model_kwargs={\"ov_config\": ov_config, \"trust_remote_code\": True},\n",
    "    generate_kwargs={\"temperature\": 0.7, \"top_k\": 50, \"top_p\": 0.95},\n",
    "    completion_to_prompt=completion_to_prompt,\n",
    "    device_map=llm_device.value,\n",
    ")\n",
    "\n",
    "response = llm.complete(\"2 + 2 =\")\n",
    "print(str(response))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "eb9a794c-1fd2-4586-91b6-6aa2b4bb6c64",
   "metadata": {},
   "source": [
    "## Run QA over Document\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "A typical RAG application has two main components:\n",
    "\n",
    "- **Indexing**: a pipeline for ingesting data from a source and indexing it. This usually happen offline.\n",
    "\n",
    "- **Retrieval and generation**: the actual RAG chain, which takes the user query at run time and retrieves the relevant data from the index, then passes that to the model.\n",
    "\n",
    "The most common full sequence from raw data to answer looks like:\n",
    "\n",
    "**Indexing**\n",
    "\n",
    "1. `Load`: First we need to load our data. We’ll use DocumentLoaders for this.\n",
    "2. `Split`: Text splitters break large Documents into smaller chunks. This is useful both for indexing data and for passing it in to a model, since large chunks are harder to search over and won’t in a model’s finite context window.\n",
    "3. `Store`: We need somewhere to store and index our splits, so that they can later be searched over. This is often done using a VectorStore and Embeddings model.\n",
    "\n",
    "![Indexing pipeline](https://github.com/openvinotoolkit/openvino_notebooks/assets/91237924/dfed2ba3-0c3a-4e0e-a2a7-01638730486a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ada4f233",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.core import VectorStoreIndex, StorageContext\n",
    "from llama_index.core.node_parser import SentenceSplitter\n",
    "from llama_index.core import Settings\n",
    "from llama_index.readers.file import PyMuPDFReader\n",
    "from llama_index.vector_stores.faiss import FaissVectorStore\n",
    "from transformers import StoppingCriteria, StoppingCriteriaList\n",
    "import faiss\n",
    "import torch\n",
    "\n",
    "if model_language.value == \"English\":\n",
    "    text_example_path = \"text_example_en.pdf\"\n",
    "else:\n",
    "    text_example_path = \"text_example_cn.pdf\"\n",
    "\n",
    "\n",
    "class StopOnTokens(StoppingCriteria):\n",
    "    def __init__(self, token_ids):\n",
    "        self.token_ids = token_ids\n",
    "\n",
    "    def __call__(self, input_ids: torch.LongTensor, scores: torch.FloatTensor, **kwargs) -> bool:\n",
    "        for stop_id in self.token_ids:\n",
    "            if input_ids[0][-1] == stop_id:\n",
    "                return True\n",
    "        return False\n",
    "\n",
    "\n",
    "if stop_tokens is not None:\n",
    "    if isinstance(stop_tokens[0], str):\n",
    "        stop_tokens = llm._tokenizer.convert_tokens_to_ids(stop_tokens)\n",
    "    stop_tokens = [StopOnTokens(stop_tokens)]\n",
    "\n",
    "loader = PyMuPDFReader()\n",
    "documents = loader.load(file_path=text_example_path)\n",
    "\n",
    "faiss_index = faiss.IndexFlatL2(EMBEDDING_MODEL_HIDDEN_SIZE)\n",
    "Settings.embed_model = embedding\n",
    "\n",
    "llm.max_new_tokens = 1024\n",
    "if stop_tokens is not None:\n",
    "    llm._stopping_criteria = StoppingCriteriaList(stop_tokens)\n",
    "Settings.llm = llm\n",
    "\n",
    "vector_store = FaissVectorStore(faiss_index=faiss_index)\n",
    "storage_context = StorageContext.from_defaults(vector_store=vector_store)\n",
    "index = VectorStoreIndex.from_documents(\n",
    "    documents,\n",
    "    storage_context=storage_context,\n",
    "    transformations=[SentenceSplitter(chunk_size=200, chunk_overlap=40)],\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "25dd85bf-6156-4f3b-8042-57a0c2543d33",
   "metadata": {},
   "source": [
    "**Retrieval and generation**\n",
    "\n",
    "1. `Retrieve`: Given a user input, relevant splits are retrieved from storage using a Retriever.\n",
    "2. `Generate`: A LLM produces an answer using a prompt that includes the question and the retrieved data.\n",
    "\n",
    "![Retrieval and generation pipeline](https://github.com/openvinotoolkit/openvino_notebooks/assets/91237924/f0545ddc-c0cd-4569-8c86-9879fdab105a)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "id": "e6761ede-e007-4418-b6c8-e6c2e73f54dc",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/ethan/intel/openvino_notebooks/openvino_env/lib/python3.11/site-packages/transformers/generation/configuration_utils.py:515: UserWarning: `do_sample` is set to `False`. However, `temperature` is set to `0.7` -- this flag is only used in sample-based generation modes. You should set `do_sample=True` or unset `temperature`.\n",
      "  warnings.warn(\n",
      "/home/ethan/intel/openvino_notebooks/openvino_env/lib/python3.11/site-packages/transformers/generation/configuration_utils.py:520: UserWarning: `do_sample` is set to `False`. However, `top_p` is set to `0.95` -- this flag is only used in sample-based generation modes. You should set `do_sample=True` or unset `top_p`.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "\n",
      "Intel vPro® Enterprise systems can offer a range of advanced security features to protect network infrastructure. These include network security appliances, secure access service edge (SASE), next-generation firewall (NGFW), real-time deep packet inspection, antivirus, intrusion prevention and detection, and SSL/TLS inspection. These systems support more devices, users, and key capabilities such as real-time threat detection while processing higher network throughput. They also drive advanced security features for growing network infrastructure with enhanced power efficiency and density.\n",
      "\n",
      "Intel QuickAssist Technology (Intel QAT) accelerates and offloads key encryption/compression workloads from the CPU to free up CPU cycles. Trusted execution environments (TEEs) with Intel Software Guard Extensions (Intel SGX) and Intel Trust Domain Extensions (Intel TDX) help protect network workloads and encryption keys across edge-to-cloud infrastructure.\n",
      "\n",
      "In industrial and energy sectors, Intel vPro® Enterprise systems improve manageability and help reduce the operational costs of automation and control systems. Hardened platforms ensure system reliability in extreme conditions, and high core density provides more dedicated resources to VMs.\n",
      "\n",
      "Intel vPro® Enterprise systems also offer higher performance per watt, one-core density, and faster DDR5 memory bandwidth to enhance throughput and efficiency for edge security workloads. Intel QuickAssist Technology (Intel QAT) accelerates and offloads key encryption/compression workloads from the CPU to free up CPU cycles. Trusted execution environments (TEEs) with Intel Software Guard Extensions (Intel SGX) and Intel Trust Domain Extensions (Intel TDX) harden platforms from unauthorized access.\n",
      "\n",
      "Cache Allocation Technology (CAT) within the Intel® Resource Director Technology (Intel® RDT) framework enables performance prioritization for key applications to help meet real-time deterministic requirements.\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "query_engine = index.as_query_engine(streaming=True, similarity_top_k=10, node_postprocessors=[reranker])\n",
    "if model_language.value == \"English\":\n",
    "    query = \"What can Intel vPro® Enterprise systems offer?\"\n",
    "else:\n",
    "    query = \"英特尔博锐® Enterprise系统提供哪些功能？\"\n",
    "\n",
    "streaming_response = query_engine.query(query)\n",
    "streaming_response.print_response_stream()"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "d237c92d-2333-400e-8179-16bd797b3d15",
   "metadata": {},
   "source": [
    "## Gradio Demo\n",
    "\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "Now, when model created, we can setup Chatbot interface using [Gradio](https://www.gradio.app/).\n",
    "\n",
    "First we can check the default prompt template in LlamaIndex pipeline."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "id": "95ee1c1a-d384-4b1d-8834-d0d9be92ba02",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/markdown": [
       "**Prompt Key**: response_synthesizer:text_qa_template<br>**Text:** <br>"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Context information is below.\n",
      "---------------------\n",
      "{context_str}\n",
      "---------------------\n",
      "Given the context information and not prior knowledge, answer the query.\n",
      "Query: {query_str}\n",
      "Answer: \n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "<br><br>"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/markdown": [
       "**Prompt Key**: response_synthesizer:refine_template<br>**Text:** <br>"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The original query is as follows: {query_str}\n",
      "We have provided an existing answer: {existing_answer}\n",
      "We have the opportunity to refine the existing answer (only if needed) with some more context below.\n",
      "------------\n",
      "{context_msg}\n",
      "------------\n",
      "Given the new context, refine the original answer to better answer the query. If the context isn't useful, return the original answer.\n",
      "Refined Answer: \n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "<br><br>"
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "prompts_dict = query_engine.get_prompts()\n",
    "\n",
    "\n",
    "def display_prompt_dict(prompts_dict):\n",
    "    for k, p in prompts_dict.items():\n",
    "        text_md = f\"**Prompt Key**: {k}<br>\" f\"**Text:** <br>\"\n",
    "        display(Markdown(text_md))\n",
    "        print(p.get_template())\n",
    "        display(Markdown(\"<br><br>\"))\n",
    "\n",
    "\n",
    "display_prompt_dict(prompts_dict)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f68df69a",
   "metadata": {},
   "outputs": [],
   "source": [
    "from langchain.text_splitter import RecursiveCharacterTextSplitter\n",
    "from llama_index.core.node_parser import LangchainNodeParser\n",
    "import gradio as gr\n",
    "\n",
    "TEXT_SPLITERS = {\n",
    "    \"SentenceSplitter\": SentenceSplitter,\n",
    "    \"RecursiveCharacter\": RecursiveCharacterTextSplitter,\n",
    "}\n",
    "\n",
    "\n",
    "def default_partial_text_processor(partial_text: str, new_text: str):\n",
    "    \"\"\"\n",
    "    helper for updating partially generated answer, used by default\n",
    "\n",
    "    Params:\n",
    "      partial_text: text buffer for storing previosly generated text\n",
    "      new_text: text update for the current step\n",
    "    Returns:\n",
    "      updated text string\n",
    "\n",
    "    \"\"\"\n",
    "    partial_text += new_text\n",
    "    return partial_text\n",
    "\n",
    "\n",
    "text_processor = llm_model_configuration.get(\"partial_text_processor\", default_partial_text_processor)\n",
    "\n",
    "\n",
    "def create_vectordb(doc, spliter_name, chunk_size, chunk_overlap, vector_search_top_k, vector_rerank_top_n, run_rerank):\n",
    "    \"\"\"\n",
    "    Initialize a vector database\n",
    "\n",
    "    Params:\n",
    "      doc: orignal documents provided by user\n",
    "      chunk_size:  size of a single sentence chunk\n",
    "      chunk_overlap: overlap size between 2 chunks\n",
    "      vector_search_top_k: Vector search top k\n",
    "      vector_rerank_top_n: Rerrank top n\n",
    "      run_rerank: whether to run reranker\n",
    "\n",
    "    \"\"\"\n",
    "    global query_engine\n",
    "    global index\n",
    "\n",
    "    if vector_rerank_top_n > vector_search_top_k:\n",
    "        gr.Warning(\"Search top k must >= Rerank top n\")\n",
    "\n",
    "    loader = PyMuPDFReader()\n",
    "    documents = loader.load(file_path=doc.name)\n",
    "    spliter = TEXT_SPLITERS[spliter_name](chunk_size=chunk_size, chunk_overlap=chunk_overlap)\n",
    "    if spliter_name == \"RecursiveCharacter\":\n",
    "        spliter = LangchainNodeParser(spliter)\n",
    "    faiss_index = faiss.IndexFlatL2(d)\n",
    "    vector_store = FaissVectorStore(faiss_index=faiss_index)\n",
    "    storage_context = StorageContext.from_defaults(vector_store=vector_store)\n",
    "\n",
    "    index = VectorStoreIndex.from_documents(\n",
    "        documents,\n",
    "        storage_context=storage_context,\n",
    "        transformations=[spliter],\n",
    "    )\n",
    "    if run_rerank:\n",
    "        reranker.top_n = vector_rerank_top_n\n",
    "        query_engine = index.as_query_engine(streaming=True, similarity_top_k=vector_search_top_k, node_postprocessors=[reranker])\n",
    "    else:\n",
    "        query_engine = index.as_query_engine(streaming=True, similarity_top_k=vector_search_top_k)\n",
    "\n",
    "    return \"Vector database is Ready\"\n",
    "\n",
    "\n",
    "def update_retriever(vector_search_top_k, vector_rerank_top_n, run_rerank):\n",
    "    \"\"\"\n",
    "    Update retriever\n",
    "\n",
    "    Params:\n",
    "      vector_search_top_k: size of searching results\n",
    "      vector_rerank_top_n:  size of rerank results\n",
    "      run_rerank: whether run rerank step\n",
    "\n",
    "    \"\"\"\n",
    "    global query_engine\n",
    "\n",
    "    if vector_rerank_top_n > vector_search_top_k:\n",
    "        gr.Warning(\"Search top k must >= Rerank top n\")\n",
    "\n",
    "    if run_rerank:\n",
    "        reranker.top_n = vector_rerank_top_n\n",
    "        query_engine = index.as_query_engine(streaming=True, similarity_top_k=vector_search_top_k, node_postprocessors=[reranker])\n",
    "    else:\n",
    "        query_engine = index.as_query_engine(streaming=True, similarity_top_k=vector_search_top_k)\n",
    "\n",
    "\n",
    "def bot(history, temperature, top_p, top_k, repetition_penalty, do_rag):\n",
    "    \"\"\"\n",
    "    callback function for running chatbot on submit button click\n",
    "\n",
    "    Params:\n",
    "      history: conversation history\n",
    "      temperature:  parameter for control the level of creativity in AI-generated text.\n",
    "                    By adjusting the `temperature`, you can influence the AI model's probability distribution, making the text more focused or diverse.\n",
    "      top_p: parameter for control the range of tokens considered by the AI model based on their cumulative probability.\n",
    "      top_k: parameter for control the range of tokens considered by the AI model based on their cumulative probability, selecting number of tokens with highest probability.\n",
    "      repetition_penalty: parameter for penalizing tokens based on how frequently they occur in the text.\n",
    "      do_rag: whether do RAG when generating texts.\n",
    "\n",
    "    \"\"\"\n",
    "    llm.generate_kwargs = dict(\n",
    "        temperature=temperature,\n",
    "        do_sample=temperature > 0.0,\n",
    "        top_p=top_p,\n",
    "        top_k=top_k,\n",
    "        repetition_penalty=repetition_penalty,\n",
    "    )\n",
    "\n",
    "    partial_text = \"\"\n",
    "    if do_rag:\n",
    "        streaming_response = query_engine.query(history[-1][0])\n",
    "        for new_text in streaming_response.response_gen:\n",
    "            partial_text = text_processor(partial_text, new_text)\n",
    "            history[-1][1] = partial_text\n",
    "            yield history\n",
    "    else:\n",
    "        streaming_response = llm.stream_complete(history[-1][0])\n",
    "        for new_text in streaming_response:\n",
    "            partial_text = text_processor(partial_text, new_text.delta)\n",
    "            history[-1][1] = partial_text\n",
    "            yield history\n",
    "\n",
    "\n",
    "def request_cancel():\n",
    "    llm._model.request.cancel()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d2663dfb-5318-4e53-8697-4fa49c8809b6",
   "metadata": {},
   "outputs": [],
   "source": [
    "if not Path(\"gradio_helper.py\").exists():\n",
    "    r = requests.get(url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/notebooks/llm-rag-llamaindex/gradio_helper.py\")\n",
    "    open(\"gradio_helper.py\", \"w\").write(r.text)\n",
    "\n",
    "from gradio_helper import make_demo\n",
    "\n",
    "demo = make_demo(\n",
    "    load_doc_fn=create_vectordb,\n",
    "    run_fn=bot,\n",
    "    stop_fn=request_cancel,\n",
    "    update_retriever_fn=update_retriever,\n",
    "    model_name=llm_model_id.value,\n",
    "    language=model_language.value,\n",
    "    rerank_device=rerank_device.value,\n",
    ")\n",
    "\n",
    "try:\n",
    "    demo.queue().launch(debug=True)\n",
    "except Exception:\n",
    "    demo.queue().launch(share=True, debug=True)\n",
    "# If you are launching remotely, specify server_name and server_port\n",
    "# EXAMPLE: `demo.launch(server_name='your server name', server_port='server port in int')`\n",
    "# To learn more please refer to the Gradio docs: https://gradio.app/docs/"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.4"
  },
  "openvino_notebooks": {
   "imageUrl": "https://github.com/openvinotoolkit/openvino_notebooks/assets/91237924/16155d31-c3e2-4b43-87f0-9b17c43aca6b",
   "tags": {
    "categories": [
     "Model Demos",
     "AI Trends"
    ],
    "libraries": [],
    "other": [
     "LLM"
    ],
    "tasks": [
     "Text Generation"
    ]
   }
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
